package com.han.walkman.controller;

import com.han.walkman.entity.DataBackEntity;
import com.han.walkman.entity.VisitedPlanEntity;
import com.han.walkman.service.VisitedPlanService;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: Hanjiafeng
 * @Date: 2020/5/15
 * @Desc:
 */
@RestController
@RequestMapping("/visitedPlan")
public class VisitedPlanController {

    private final VisitedPlanService visitedPlanService;

    public VisitedPlanController(VisitedPlanService visitedPlanService) {
        this.visitedPlanService = visitedPlanService;
    }

    /**
     * 分页查询
     *
     * @return list
     */
    @GetMapping("/findByKeyword")
    public DataBackEntity<Page<VisitedPlanEntity>> findByPage(String userId, String keyword, Integer index, Integer size) {

        int userIdInt;
        try {
            userIdInt = Integer.parseInt(userId);
            if (userIdInt == -1) {
                throw new NumberFormatException();
            }
        } catch (NumberFormatException e) {
            return new DataBackEntity<>(0, "请登录后查看", null);
        }

        //构建搜索条件
        ExampleMatcher exampleMatcher = ExampleMatcher.matching()
                //包含字符串
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING);
        VisitedPlanEntity entity = new VisitedPlanEntity();
        entity.setUserId(userIdInt);
        entity.setTitle(keyword);
        Example<VisitedPlanEntity> entityExample = Example.of(entity, exampleMatcher);

        Pageable pageable = PageRequest.of(index, size);
        Page<VisitedPlanEntity> visitedPlanEntityPage = visitedPlanService.findAll(entityExample, pageable);
        return new DataBackEntity<>(1, "查询历史拜访记录成功", visitedPlanEntityPage);
    }
}